package com.example.lotterysystem.dao.mapper;

import com.example.lotterysystem.dao.dataobject.PhoneEncrypt;
import com.example.lotterysystem.dao.dataobject.UserDO;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper {
    /**
     * 查询邮箱是否存在
     * @param email
     * @return
     */
    @Select("select count(*) from user where email = #{email}")
    int countByEmail(@Param("email") String email);

    /**
     * 查看手机号是否已存在
     * @param phoneNumber
     * @return
     */
    @Select(("select count(*) from user where phone_number = #{phoneNumber}"))
    int countByPhone(@Param("phoneNumber")PhoneEncrypt phoneNumber);

    /**
     * 新增注册用户
     */
    @Insert("insert into user(user_name, email, phone_number, password, identity) " +
            "values (#{userName}, #{email}, #{phoneNumber}, #{password}, #{identity})")
    @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
    void insert(UserDO userDO);

    /**
     * 通过手机号查询用户信息
     * @param phoneNumber
     * @return
     */
    @Select("select id, gmt_create, gmt_modified, user_name, email, phone_number, password, identity from user where phone_number = #{phoneNumber}")
    UserDO selectByPhoneNumber(PhoneEncrypt phoneNumber);

    /**
     * 通过邮箱查询用户信息
     * @param email
     * @return
     */
    @Select("select id, gmt_create, gmt_modified, user_name, email, phone_number, password, identity from user where email = #{email}")
    UserDO selectByEmail(String email);

    /**
     * 查询身份信息为 identity 的所有用户
     * @param identity
     * @return
     */
    @Select("<script>" +
            " select id, gmt_create, gmt_modified, user_name, email, phone_number, password, identity" +
            " from user " +
            " <if test = \"identity != null\">" +
            "    where identity = #{identity} " +
            " </if>" +
            " order by id desc " +
            " </script>")
    List<UserDO> selectByIdentity(String identity);

    @Select("<script>" +
            " select id " +
            " from user " +
            " where id in " +
            " <foreach item = 'item' collection='items' open='(' separator=',' close=')'> " +
            " #{item}" +
            " </foreach>" +
            " </script>")
    List<Long> selectExistByIds(@Param("items") List<Long> userIds);

    @Select("<script>" +
            " select * " +
            " from user " +
            " where id in " +
            " <foreach item = 'item' collection='items' open='(' separator=',' close=')'> " +
            " #{item}" +
            " </foreach>" +
            " </script>")
    List<UserDO> selectByIds(@Param("items") List<Long> userIds);
}
